<?php
require_once(LIB_PATH.'/log/mylog.php');//登录

class myxiaochengxu
{
    public static $data = [];//模板消息的关键字
    public static $msg = [];//模板消息的关键字

    //生成推广的朋友圈图片
    //注意需要把tbl_qr_template表导入
    public static function promotionQr($templateId,$qrFile,$title,$desc){
        $template = new QrTemplate();
        if($templateId){
            $template->qrTemplateId =$templateId;
        }else{
            $template->qrTemplateId = r('qrTemplateId');
        }
        $find =  $template->find();
        if(!$find){
            j(["code"=>-1,"info"=>"没有找到模板",['qrTemplateId'=>$templateId]]);
        }

        // 图片一,png
        $path_1 = ROOT_PATH."web/".$template->img;
        // 创建图片对象
        $image_1 = imagecreatefrompng($path_1);
        $image_2 = imagecreatefromjpeg($qrFile);
        // 创建真彩画布
        $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));
        // 为真彩画布创建白色背景
        $color = imagecolorallocate($image_3, 0, 0, 0);
        imagefill($image_3, 0, 0, $color);
        // 设置透明
        imageColorTransparent($image_3, $color);
        // 复制图片一到真彩画布中（重新取样-获取透明图片）
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
        // 与图片二合成
        $srcX = 0;
        $srcY = 0;
        imagecopymerge($image_3, $image_2, $template->qrX, $template->qrY, $srcX, $srcY, imagesx($image_2), imagesy($image_2), 100);

        //$font = LIB_PATH.'font/yahei.ttf';//字体路径
        //$black = imagecolorallocate($image_3, 0x00, 0x00, 0x00);//字体颜色
        //imagefttext($image_3, 50, 0, $template->titleX, $template->titleY, $black, $font, 'ceshi 策划');

        $font = LIB_PATH.'font/yahei.ttf';//字体路径
        $black = imagecolorallocate($image_3, 0x00, 0x00, 0x00);//字体颜色
        imagefttext($image_3, 36, 0, $template->titleX, $template->titleY, $black, $font,$title);
        imagefttext($image_3, 28, 0, $template->descX, $template->descY, $black, $font, $desc);

        // 输出合成图片
        $up = "up/".uniqid().".png";
        imagepng($image_3, FRONT_ROOT."web/$up");

        if(!r('isDebug')){
            header('Content-Type: image/jpg');
            //imagejpeg($im,$filename);
            imagejpeg($image_3);
        }
        imagedestroy($image_1);
        imagedestroy($image_2);
        imagedestroy($image_3);

        return $up;
    }

    //https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
    public static function qrTemp($scene,$page,$width=280){
        if($width < 280) $width = 280;
        if($width > 1280) $width = 1280;

        //增加缓存检查，每分钟腾讯有此数限制
        $fileName = "up/qr_".md5($scene."_{$page}_"."_{$width}").".png";
        if(file_exists(ROOT_PATH."web/$fileName") && filesize(ROOT_PATH."web/$fileName") > 1000){//判断文件存在并且有一定大小
            return $fileName;
        }

        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $ajax = [
            "scene"  => $scene,
            "page"   => $page,
            "width"  => $width
        ];

        $result = myspider::ajax($url,$ajax);

        file_put_contents(ROOT_PATH."web/$fileName",$result);
        return $fileName;
    }

    //客服消息接口
    //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/customer-message/customerServiceMessage.send.html
    public static function sendXiaochengxuCard($toOpenId,$msg){
        $msgType = "miniprogrampage";
        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";

        $data['msgtype'] = $msgType;
        $data['touser'] = $toOpenId;

        $data['miniprogrampage']['title'] = $msg;
        $data['miniprogrampage']['pagepath'] = "pages/index/index";
        $data['miniprogrampage']['thumb_media_id'] = "AKoMTvASOU54ZM3xDRw5Qt0LTDHv7zcQIgVz_dgmOzoZxkMBONW5NxQ6f9YplZgx";//通过后台先上传,客服小程序卡片

        $content = myspider::ajax($url,$data);
        if(r('isDebug')){
            print_r($content);
        }
    }

    //自定义idx的时候最小是1
    public static function addTemplateKeyword($msg,$idxFrom1=0,$color="#000000"){
        if(!$idxFrom1){
            $idxFrom1 = count(self::$data)+1;
        }
        self::$data['keyword'.$idxFrom1]['value'] = $msg;
        self::$data['keyword'.$idxFrom1]['color'] = $color;

    }


    //模板消息接口
    //https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html
    //测试连接
    //https://zhaopeixunapi.hkbao.com/message,send?fromUid=28&toUid=28&msg=good&key=111&time=11111111&isDebug=1
    public static function sendTemplateMsg($toOpenId,$templateId,$page=""){
        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$token";

        $data['touser'] = $toOpenId;
        $data['template_id'] = $templateId;
        $data['form_id'] = self::getFormId($toOpenId);
        if(!$data['form_id']){
            self::$msg = ["errcode"=>-1,'errmsg'=>'no form_id'];
            return -1;
        }

        if($page) $data['page'] = $page;

        $data['data'] = self::$data;
        $content = myspider::ajax($url,$data);
        if(r('isDebug')){
            print_r($content);
        }
        $rect = json_decode($content);
        self::$msg = $rect;

        return $rect->errcode;
    }

    public static function getErrorInfo(){
        return self::$msg;
    }

    public static function getFormId($toOpenId){
        $user = new User();
        $user->openId = $toOpenId;
        $user->find();

        //7天之内的
        $messageKeyObj = new MessageKey();
        $time = time() - 7*24*3600+5;//7天内的,5秒误差
        $lastTime = date('Y-m-d H:i:s',$time);
        //https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/template-message.html 表单可以发一条模板消息
        $sql = "SELECT * FROM ". $messageKeyObj->table()." WHERE uid=".$user->uid." AND created>'$lastTime' AND orderId=0 AND usedCount=0 ORDER BY ".$messageKeyObj->key()." DESC LIMIT 1";//表单
        $one = $messageKeyObj->one($sql);
        if($one){
            $messageKeyObj->usedCount = 1;
            $saved = $messageKeyObj->save();
            return $messageKeyObj->messageKey;
        }

        //订单可以发三次
        $sql = "SELECT * FROM ". $messageKeyObj->table()." WHERE uid=".$user->uid." AND created>'$lastTime' AND orderId!=0 AND usedCount<3 ORDER BY ".$messageKeyObj->key()." DESC LIMIT 1";//订单
        $one = $messageKeyObj->one($sql);
        if($one){
            $messageKeyObj->usedCount = $messageKeyObj->usedCount + 1;
            $saved = $messageKeyObj->save();
            return $messageKeyObj->messageKey;
        }

        return false;
    }

    //客服消息接口
    //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/customer-message/customerServiceMessage.send.html
    //测试连接
    //https://zhaopeixunapi.hkbao.com/message,send?fromUid=28&toUid=28&msg=good&key=111&time=11111111&isDebug=1
    public static function sendMsg($toOpenId,$msg){
        $token = mygongzhonghao::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";

        $data['touser'] = $toOpenId;
        $data['msgtype'] = "text";
        $data['text']['content'] = $msg."<a href=\"".FRONT_URL."\" data-miniprogram-appid=\"".WEIXIN_APPID."\" data-miniprogram-path=\"pages/index/index\">点击跳转小程序</a>";
        $content = myspider::ajax($url,$data);
        if(r('isDebug')){
            print_r($content);
        }
    }


    public function valid()  //第一次验证服务器用
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    /**
        //正常返回的JSON数据包
        {
        "openid": "OPENID",
        "session_key": "SESSIONKEY",
        }

        //满足UnionID返回条件时，返回的JSON数据包
        {
        "openid": "OPENID",
        "session_key": "SESSIONKEY",
        "unionid": "UNIONID"
        }
        //错误时返回JSON数据包(示例为Code无效)
        {
        "errcode": 40029,
        "errmsg": "invalid code"
        }
     */
    //https://developers.weixin.qq.com/miniprogram/dev/api/wx.login.html
    //https://developers.weixin.qq.com/miniprogram/dev/api-backend/auth.code2Session.html
    public static function getBaseInfo($code){
        $appId = WEIXIN_APPID; //对应小程序的appid
        $secret = WEIXIN_SECRET; //对应小程序的sec
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secret.'&js_code=' . $code . '&grant_type=authorization_code';
        $json = json_decode(myspider::openFile($url));
        return $json;
    }

    public static function getOpenId($code){
        $json = self::getBaseInfo($code);
        return $json->openid;
    }

    public static function getSessionKey($code){
        $json = self::getBaseInfo($code);
        return $json->session_key;
    }

    public static function getMobile($encryptedData,$sessionKey,$iv){
        require_once(__DIR__.'/wxBizDataCrypt.php');
        $appid = WEIXIN_APPID;
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $data = '';//解密后的返回值
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
	$data = json_decode($data);

        if ($errCode == 0) {
            return $data->phoneNumber;
        } else {
            return '';
        }
    }

    public function getVisitData(){

    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            //mylog::write(__FILE__.__LINE__."OK:".$signature.' == '.$tmpStr);
            return true;
        }else{
            //mylog::write(__FILE__.__LINE__."error:".$signature.' != '.$tmpStr);
            return false;
        }
    }

    //发送文本
    public function sendText($toUserName,$content){
        $data=array(
            "touser"=>$toUserName,
            "msgtype"=>"text",
            "text"=>array("content"=>$content)
        );
        $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //PHP版本5.4以上
        $this->post2($json);
    }

    //发送图片素材
    public function sendImage($toUserName,$mediaId){
        $data=array(
            "touser"=>$toUserName,
            "msgtype"=>"image",
            "image"=>array("media_id"=>$mediaId)
        );
        $json = json_encode($data,JSON_UNESCAPED_UNICODE);
        $this->post2($json);
    }

    //发送欢迎词
    public function sendWelcome($toUserName){
        $content = '吃了么！';
        $data=array(
            "touser"=>$toUserName,
            "msgtype"=>"text",
            "text"=>array("content"=>$content)
        );
        $json = json_encode($data,JSON_UNESCAPED_UNICODE);
        $this->post2($json);
    }


    public function responseMsg()
    {
        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据
        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);
            $fromUsername = $postArr['FromUserName'];   //发送者openid

            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用户发送文本消息
                $content = '中文';   //输入想要回复
                $this->sendText($fromUsername,$content);
            }else if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
                $mediaId = '';   //输入想要回复的图片消息的media_id
               $this->sendImage($fromUsername,$mediaId);
            }else if($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服
                $this->sendWelcome($fromUsername);
            }
        }
    }


    public static function  getMsg() {
        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据
        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);
            return $postArr;
        }
    }


    //获取access_token/* 调用微信api，获取access_token，有效期7200s*/
    public function Curl() {
        $appid=WEIXIN_APPID;
        $appsecret=WEIXIN_SECRET;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; //替换成自己的小程序id和secret
        $result = file_get_contents($url);
        $res = json_decode($result,true);   //json字符串转数组
        return $res['access_token'];
    }

    //更新access_token存储到数据库并返回数据
    public function getToken(){
        $db = new mydb();
        $times=time();//当前时间
        $sql="select A_ID,A_Token,A_Date from wx_anran_accesstoken order by A_ID desc";
        $row = $db->getOne($sql);
        if ($row) {
            if($row['A_Date'] < $times){
                $token= $this->Curl();
                $timestamp=time()+7100;
                $sqlu="UPDATE `wx_anran_accesstoken` SET `A_Token`='$token',`A_Date`='$timestamp' WHERE A_ID = '{$row['A_ID']}' ";
                $db->query($sqlu);
                return $token;
            }else{//没超过，则从数据库取
                return $row['A_Token'];
            }
        }else{
            $timestamp=time()+7100;
            $token= $this->Curl();
            $sqlin="insert into wx_anran_accesstoken(A_Token,A_Date) values('$token','$timestamp')";
            //mylog::write(__FILE__.__LINE__." insert:".$sqlin);
            $db->query($sqlin);
            return $token;
        }
    }
    //向客户端发送回复消息
    public function post2($data){
        $access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: text',
                'content' => $data
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        //mylog::write(__FILE__.__LINE__." insert:".$context);
        return $result;
    }




}
